package com.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.mapper.PersonTrainMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.PersonVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@Controller
@RequestMapping("/api/train")
public class PersonTrainController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private PersonService personService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PersonPositionService personPositionService;
    @Autowired
    private PersonTrainService personTrainService;
    @Autowired
    private PersonTrainMapper personTrainMapper;
    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        CategoryVo vo = new CategoryVo();

        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(35);
        vo.setTrainDescList(categoryModelList);
        List<CategoryModel> categoryModelList1 = categoryService.getCategoryByPid(53);
        vo.setTrainObjectList(categoryModelList1);
        List<CategoryModel> categoryModelList2 = categoryService.getCategoryByPid(50);
        vo.setTrainLevelList(categoryModelList2);

        return Result.success(vo);
    }

    @GetMapping("/getTrainList")//军事训练管理分页查询
    public Result<Object> getTrainList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam("name") String name,
            Integer year,
            HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        Page<PersonModel> getPageTrainList = personService.getPageTrainList(page, limit, name, idList);
        for (int i = 0; i < getPageTrainList.getRecords().size(); i++) {
            if (getPageTrainList.getRecords().get(i).getDepartmentId() != null) {
                DepartmentModel model2 = departmentService.getDepByDepId(getPageTrainList.getRecords().get(i).getDepartmentId());
                if (model2 != null) {
                    getPageTrainList.getRecords().get(i).setDepartmentText(model2.getName());//部门名称
                }
            }
            List<PersonTrainModel> trainModelList = personTrainService.getTrainList(getPageTrainList.getRecords().get(i).getId(), year);
            if (trainModelList.size() > 0) {
                List<PersonTrainModel> list = new ArrayList<>();
                for (int j = 0; j < trainModelList.size(); j++) {
                    CategoryModel model1 = categoryService.getCategoryById(trainModelList.get(j).getTrainDesc());
                    if (model1 != null) {
                        getPageTrainList.getRecords().get(i).setTrainDesc(model1.getId());
                        getPageTrainList.getRecords().get(i).setTrainDescText(model1.getName());//训练总成绩
                    }
                    String trainResult = trainModelList.get(j).getTrainResult();
                    list = JSON.parseObject(trainResult, new TypeReference<List<PersonTrainModel>>() {
                    });
                }
                getPageTrainList.getRecords().get(i).setTrainList(list);
            }
        }
        if (getPageTrainList == null) {
            return Result.error(200, "暂无数据");
        }
        int count = (int) getPageTrainList.getTotal();
        List<PersonModel> trainModelList;
        trainModelList = getPageTrainList.getRecords();
        PersonVo vo = new PersonVo();
        vo.setList(trainModelList);
        vo.setCount(count);
        return Result.success(vo);
    }

    @PostMapping("/insertTrain")//新增/修改职务
    public Result<Object> insertTrain(@RequestBody PersonTrainModel personTrainModel) throws JsonProcessingException {
        PersonTrainModel model = new PersonTrainModel();
        if (personTrainModel.getIsCreate() == 0) {
            List<PersonTrainModel> trainList = personTrainModel.getTrainList();
            if (!trainList.isEmpty()) {
                model.setPersonId(personTrainModel.getPersonId());
                model.setTrainDesc(personTrainModel.getTrainDesc());
                model.setYear(personTrainModel.getYear());
                model.setTrainResult(JSON.toJSONString(trainList));
                personTrainService.insert(model);
            }
        } else if (personTrainModel.getIsCreate() == 1) {
            List<PersonTrainModel> trainAdd = personTrainModel.getTrainAdd();
            List<PersonTrainModel> trainEdit = personTrainModel.getTrainEdit();
            String trainRemove = personTrainModel.getTrainRemove();
            if (trainAdd.isEmpty() && trainEdit.isEmpty() && trainRemove.equals("")) {
                QueryWrapper<PersonTrainModel> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", personTrainModel.getPersonId());
                queryWrapper.eq("year", personTrainModel.getYear());
                PersonTrainModel personTrainModel1 = personTrainMapper.selectOne(queryWrapper);
                if (personTrainModel1 == null) {
                    model.setPersonId(personTrainModel.getPersonId());
                    model.setTrainDesc(personTrainModel.getTrainDesc());
                    model.setYear(personTrainModel.getYear());
                    personTrainService.insert(model);
                }
            }
            if (!trainAdd.isEmpty()) {
                for (int i = 0; i < trainAdd.size(); i++) {
                    int ran = (int) (Math.random() * 999);
                    trainAdd.get(i).setId(ran);
                }
                QueryWrapper<PersonTrainModel> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", personTrainModel.getPersonId());
                queryWrapper.eq("year", personTrainModel.getYear());
                PersonTrainModel personTrainModel1 = personTrainMapper.selectOne(queryWrapper);
                if (personTrainModel1 != null) {
                    String trainResult = personTrainModel1.getTrainResult();
                    List<PersonTrainModel> personTrainModels = JSON.parseObject(trainResult, new TypeReference<List<PersonTrainModel>>() {
                    });
                    if (personTrainModels != null && personTrainModels.size() != 0) {
                        personTrainModels.addAll(trainAdd);
                        model.setId(personTrainModel1.getId());
                        model.setPersonId(personTrainModel.getPersonId());
                        model.setTrainDesc(personTrainModel.getTrainDesc());
                        model.setYear(personTrainModel.getYear());
                        model.setTrainResult(JSON.toJSONString(personTrainModels));
                        personTrainService.update(model);
                    } else {
                        model.setId(personTrainModel1.getId());
                        model.setPersonId(personTrainModel.getPersonId());
                        model.setTrainDesc(personTrainModel.getTrainDesc());
                        model.setYear(personTrainModel.getYear());
                        model.setTrainResult(JSON.toJSONString(trainAdd));
                        personTrainService.update(model);
                    }
                }
                if (personTrainModel1 == null) {
                    for (int i = 0; i < trainAdd.size(); i++) {
                        int ran = (int) (Math.random() * 999);
                        trainAdd.get(i).setId(ran);
                    }
                    model.setPersonId(personTrainModel.getPersonId());
                    model.setTrainDesc(personTrainModel.getTrainDesc());
                    model.setYear(personTrainModel.getYear());
                    model.setTrainResult(JSON.toJSONString(trainAdd));
                    personTrainService.insert(model);
                }
            }
            if (!trainEdit.isEmpty()) {
                QueryWrapper<PersonTrainModel> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", personTrainModel.getPersonId());
                queryWrapper.eq("year", personTrainModel.getYear());
                PersonTrainModel personTrainModel1 = personTrainMapper.selectOne(queryWrapper);
                String trainResult = personTrainModel1.getTrainResult();
                List<PersonTrainModel> personTrainModels = JSON.parseObject(trainResult, new TypeReference<List<PersonTrainModel>>() {
                });
                for (int i = 0; i < personTrainModels.size(); i++) {
                    for (int i1 = 0; i1 < trainEdit.size(); i1++) {
                        if (personTrainModels.get(i).getId().equals(trainEdit.get(i1).getId())) {
                            personTrainModels.set(i, trainEdit.get(i1));
                        }
                    }
                }
                model.setId(personTrainModel1.getId());
                model.setPersonId(personTrainModel.getPersonId());
                model.setTrainDesc(personTrainModel.getTrainDesc());
                model.setYear(personTrainModel.getYear());
                model.setTrainResult(JSON.toJSONString(personTrainModels));
                personTrainService.update(model);
            }
            if (trainRemove != null && !trainRemove.equals("")) {
                QueryWrapper<PersonTrainModel> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("person_id", personTrainModel.getPersonId());
                queryWrapper.eq("year", personTrainModel.getYear());
                PersonTrainModel personTrainModel1 = personTrainMapper.selectOne(queryWrapper);
                String trainResult = personTrainModel1.getTrainResult();
                List<PersonTrainModel> personTrainModels = JSON.parseObject(trainResult, new TypeReference<List<PersonTrainModel>>() {
                });
                String[] positionRemoveArr = trainRemove.split(",");
                for (int i = 0; i < personTrainModels.size(); i++) {
                    for (int i1 = 0; i1 < positionRemoveArr.length; i1++) {
                        if (personTrainModels.get(i).getId() == Integer.parseInt(positionRemoveArr[i1])) {
                            personTrainModels.remove(i);
                        }
                    }
                }
                model.setTrainResult(JSON.toJSONString(personTrainModels));
                model.setId(personTrainModel1.getId());
                personTrainService.update(model);

            }
        }
        return Result.success(null);
    }


    @GetMapping("/deleteTrainById")//删除考核
    public Result<Object> deleteById(
            @RequestParam("id") Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        PersonTrainModel model = personTrainService.selectTrainById(id);
        if (model == null) {
            return Result.error(500, "该职务不存在");
        } else {
            personTrainService.delete(id);
            return Result.success(null);
        }
    }

    public static Set<Integer> generateRandomNumbers(int n, int max) {
        if (n > max) {
            throw new IllegalArgumentException("n must be less than or equal to max");
        }

        Set<Integer> set = new HashSet<>();
        Random random = new Random();

        while (set.size() < n) {
            int num = random.nextInt(max) + 1;
            set.add(num);
        }

        return set;
    }
}
